package user

import (
	"context"
	"encoding/json"
	"errors"
	"google.golang.org/grpc/metadata"
	"io/ioutil"
	"net/http"
)

//通过grpc的ctx获取用户名字
func GetUserName(ctx context.Context) (string ,error) {
	type Response struct {
		Name string `json:"name"`
	}
	//获取token
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok || len(md.Get("authorization")) == 0{
		return "",errors.New("get token error")
	}
	token := md.Get("authorization")[0]
	//发送请求
	request,_ := http.NewRequest("GET","http://auth:9000/auth/get_user_info",nil)
	request.Header.Add("authorization",token)
	client := &http.Client{}
	resp,err:= client.Do(request)
	if err !=nil{return "",err}
	defer resp.Body.Close()
	if resp.StatusCode != 200{
		return "",errors.New("get user info error")
	}
	//获取用户信息
	info := Response{}
	body, _ := ioutil.ReadAll(resp.Body)
	if err = json.Unmarshal(body, &info);err != nil{
		return "",err
	}

	return info.Name, nil
}